package com.wl.flutter_app_demo;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.luck.picture.lib.basic.PictureSelectionModel;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.engine.ImageEngine;
import com.luck.picture.lib.engine.VideoPlayerEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnQueryFilterListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.language.LanguageConfig;
import com.luck.picture.lib.style.BottomNavBarStyle;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.style.SelectMainStyle;
import com.luck.picture.lib.style.TitleBarStyle;
import com.luck.picture.lib.utils.DensityUtil;
import com.ruixue.RXJSONCallback;
import com.ruixue.RuiXueSdk;
import com.ruixue.error.RXErrorCode;
import com.ruixue.leagl.PrivacyCallback;
import com.ruixue.logger.RXLogger;
import com.ruixue.oss.OSSSdkWrapper;
import com.ruixue.oss.RXProgressListener;
import com.ruixue.utils.ThreadUtils;
import com.wl.flutter_app_demo.engine.ExoPlayerEngine;
import com.wl.flutter_app_demo.engine.GlideEngine;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import pigeon.RuixuePlugin;

public class MainActivity extends FlutterActivity {

    private static final String PROGRESS_CHANNEL = "image_picker_upload_progress";
    private EventChannel.EventSink eventSink;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RuiXueSdk.trackingLifecycle(this);
        RuiXueSdk.setPrivacyAgree(b -> {

        });

        if (getFlutterEngine() != null) {
            RuixuePlugin.RuiXueApi.setup(getFlutterEngine().getDartExecutor().getBinaryMessenger(), new RuixuePlugin.RuiXueApi() {
                @Override
                public void initSdk(@NonNull RuixuePlugin.Result<RuixuePlugin.ResponseData> result) {
                    initRuiXueSdk(result);
                }

                @Override
                public void ossUpload(@NonNull String objectKey, @NonNull String filePath, @NonNull RuixuePlugin.Result<RuixuePlugin.ResponseData> result) {
                    rxUpload(objectKey, filePath, result);
                }

                @Override
                public void launchNativePhoto(@Nullable Map<String, Object> map, @NonNull RuixuePlugin.Result<RuixuePlugin.ResponseData> result) {
                    launchCustomPhoto(map, result);
                }
            });
            new EventChannel(getFlutterEngine().getDartExecutor(), PROGRESS_CHANNEL).setStreamHandler(new EventChannel.StreamHandler() {
                @Override
                public void onListen(Object arguments, EventChannel.EventSink events) {
                    eventSink = events;
                }

                @Override
                public void onCancel(Object arguments) {
                    eventSink = null;
                }
            });
        }

    }

    private void initRuiXueSdk(@NonNull RuixuePlugin.Result<RuixuePlugin.ResponseData> result) {
        // 同意隐私协议
        String cpid = "114";
        String productId = "1002";
        String channelId = "100";
        List<String> hostUrls = new ArrayList<>();
        hostUrls.add("http://cn-api-test.ruixueyun.com");

        RuiXueSdk.initialize(cpid, productId, channelId, hostUrls, new RXJSONCallback() {
            @Override
            public void onSuccess(@Nullable JSONObject jsonObject) {
                RuiXueSdk.setDebugEnabled(true);
                RXLogger.d("RXSDK 初始化成功");
                RuixuePlugin.ResponseData data = new RuixuePlugin.ResponseData();
                data.setCode(0L);
                data.setMessage("RXSDK init success");
                result.success(data);
            }

            @Override
            public void onFailed(@NonNull JSONObject jsonObject) {
                RXLogger.d("RXSDK 初始化失败 - " + jsonObject);
                int code = jsonObject.optInt("code");
                String message = jsonObject.optString("msg");
                RuixuePlugin.ResponseData data = new RuixuePlugin.ResponseData();
                data.setCode((long) code);
                data.setMessage(message);
                result.success(data);
            }
        });
    }

    private void rxUpload(@NonNull String objectKey, @NonNull String filePath, @NonNull RuixuePlugin.Result<RuixuePlugin.ResponseData> result) {
        Log.d("WLTest", "objectKey:" + objectKey  + ", filePath:" + filePath);
        ThreadUtils.getInstance().runOnBgThread(new Runnable() {
            @Override
            public void run() {

            }
        });
        if (false) {
            new Thread(() -> {
                for (int i = 0; i <= 100; i++) {
                    try {
                        Thread.sleep(100);  // 模拟上传进度
                        final double progress = i / 100.0;

                        // 在主线程中通过 EventChannel 向 Flutter 发送进度更新
                        new Handler(Looper.getMainLooper()).post(() -> {
                            if (eventSink != null) {
                                Map<String, Object> event = new HashMap<>();
                                event.put("objectKey", "test");
                                event.put("bytesWritten", progress);
                                event.put("contentLength", 1);
                                eventSink.success(event);  // 发送进度
                            }
                        });

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                // 上传结束
                RuixuePlugin.ResponseData data = new RuixuePlugin.ResponseData();
                data.setCode((long) 0);
                JSONObject json = new JSONObject();
                try {
                    json.put("url", "http://good");
                } catch (JSONException e) {
                }
                data.setData(json.toString());

                result.success(data);
            }).start();
            return;
        }
        OSSSdkWrapper.getInstance().uploadFile(MainActivity.this, objectKey, filePath, new RXJSONCallback() {
            @Override
            public void onSuccess(@Nullable JSONObject jsonObject) {
                ThreadUtils.getInstance().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (jsonObject != null) {
                            String url = jsonObject.optString("url");
                        }
                        RuixuePlugin.ResponseData data = new RuixuePlugin.ResponseData();
                        data.setCode((long) 0);
                        if (jsonObject != null) {
                            data.setData(jsonObject.toString());
                        }
                        result.success(data);
                    }
                });
            }

            @Override
            public void onFailed(@NonNull JSONObject jsonObject) {
                ThreadUtils.getInstance().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int code = jsonObject.optInt("code");
                        String message = jsonObject.optString("msg");
                        RuixuePlugin.ResponseData data = new RuixuePlugin.ResponseData();
                        data.setCode((long) code);
                        data.setMessage(message);
                        result.success(data);
                    }
                });
            }
        }, new RXProgressListener() {
            @Override
            public void onProgress(String key, long bytesWritten, long contentLength) {
                ThreadUtils.getInstance().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (eventSink != null) {
                            Map<String, Object> event = new HashMap<>();
                            event.put("objectKey", key);
                            event.put("bytesWritten", bytesWritten);
                            event.put("contentLength", contentLength);
                            eventSink.success(event);
                        }
                    }
                });

            }
        });
    }

    private Map<String, LocalMedia> localCache = new HashMap<>();

    @SuppressWarnings("unchecked")
    private void launchCustomPhoto(@Nullable Map<String, Object> map, @NonNull RuixuePlugin.Result<RuixuePlugin.ResponseData> result) {
        ArrayList<LocalMedia> originalList = null;
        try {
            if (map != null) {
                List<String> paths = (List<String>) map.get("selectPaths");
                if (paths != null) {
                    for (String path : paths) {
                        LocalMedia localMedia = localCache.get(path);
                        if (localMedia != null) {
                            if (originalList == null) {
                                originalList = new ArrayList<>();
                            }
                            originalList.add(localMedia);
                        }
                    }
                }
            }
        } catch (Exception ignore) {

        }
        if (originalList == null) {
            localCache.clear();
        }
        PictureSelector.showSelector(this, originalList, new OnResultCallbackListener<LocalMedia>() {
            @Override
            public void onResult(ArrayList<LocalMedia> list) {
                JSONArray array = new JSONArray();
                if (list != null) {
                    for (int i = 0; i < list.size(); i++) {
                        LocalMedia localMedia = list.get(i);
                        localCache.put(localMedia.getAvailablePath(), localMedia);
                        JSONObject json = new JSONObject();
                        try {
                            json.put("path", localMedia.getAvailablePath());
                            json.put("mimeType", localMedia.getMimeType());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        array.put(json);
                    }
                }
                RuixuePlugin.ResponseData data = new RuixuePlugin.ResponseData();
                data.setCode(0L);
                data.setMessage("");
                data.setData(array.toString());
                result.success(data);
            }

            @Override
            public void onCancel() {
                RuixuePlugin.ResponseData data = new RuixuePlugin.ResponseData();
                data.setCode(1L);
                data.setMessage("取消选择图片");
                result.success(data);
            }
        });
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        RuiXueSdk.onActivityResult(this, requestCode, resultCode, data);
    }
}
